﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// filters  by replacing every value by the maximum in its range  neighborhood. 
    /// </summary>
    public class MaximumFilter : BaseImageFilter
    {
        protected int m_nSizeX = 3;
        protected int m_nSizeY = 3;

        /// <summary>
        /// 
        /// </summary>
        public MaximumFilter()
        {
        }

        /// <summary>
        /// used to clone this instance
        /// </summary>
        /// <param name="_maximumFilter"></param>
        internal MaximumFilter(MaximumFilter _maximumFilter)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        public int SizeX
        {
            get { return m_nSizeX;}
            set { m_nSizeX = value; }
        }
        
        /// <summary>
        /// 
        /// </summary>
        public int SizeY
        {
            get { return m_nSizeY; }
            set { m_nSizeY = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();
            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;
            int x = 0;
            int y = 0;
            int ky = 0;
            int kx = 0;
            int nValue = 0;

            int nMin = 0;
            int nMax = 0;

            int nXLeft = m_nSizeX - 1;
            int nXRight = nWidth - (m_nSizeX - 1);
            int nYLeft = m_nSizeY - 1;
            int nYRight = nHeight - (m_nSizeY - 1);

            int nIntMaxValue = int.MaxValue;
            int nIntMinValue = int.MinValue;

            for (y = nYLeft; y < nYRight; y++)
            {
                for (x = nXLeft; x < nXRight; x++)
                {
                    nMin = nIntMaxValue;
                    nMax = nIntMinValue;

                    for (ky = 0; ky < m_nSizeY; ky++)
                    {
                        for (kx = 0; kx < m_nSizeX; kx++)
                        {
                            nValue = ColorFunctions.ToIntRGB(bitmapCloned.GetPixel(x - 1 + kx, y - 1 + ky));
                            if (nValue > nMax) nMax = nValue;
                        }
                    }

                    _bitmap.SetPixel(x, y, Color.FromArgb(255, Color.FromArgb(nMax)));
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// clones this instance
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new MaximumFilter(this);
        }
    }
}
